package org.geekbang.thinking.in.spring.ioc.overview.container;

import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * 注解能力 {@link ApplicationContext} 作为 IoC 容器示例
 *
 * @author wangyh2
 * @version v1.0
 * @since 2021-09-10 09:34
 */
@Configuration
public class AnnotationApplicationContextAsIoCContainerDemo {
    public static void main(String[] args) {
        // 1, 创建Bean容器
        AnnotationConfigApplicationContext beanFactory = new AnnotationConfigApplicationContext();
        // 2,将当前类 AnnotationApplicationContextAsIoCContainerDemo 作为配置类（Configuration Class）
        beanFactory.register(AnnotationApplicationContextAsIoCContainerDemo.class);
        // 3, 启动上下文
        beanFactory.refresh();
        // 4, 测试
        lookupCollectionByType(beanFactory);
    }

    /**
     * 通过 Java 注解的方式，定义了一个 Bean
     */
    @Bean
    public User user() {
        User user1 = new User();
        user1.setId(22L);
        user1.setName("sishen007");
        return user1;
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到的所有的 User 集合对象：" + users);
        }
    }
}
